'''
begin at 2018-7-12
last edited at 2018-7-14
MotionBar script for sky warrior flash game.
Basically, a virtual mouse.

Wrote a string parsing funtion to adapt the new data format,
and wrote a new main loop fuction.
'''
import mouse, serial

# ==============================
# datas
# ==============================


# ==============================
# functions
# ==============================
def parse_data(string):
    """
    2018-7-14 last modified
    Parse the data from original string line.
    string mode: "Bax,ay,az,gx,gy,gz,b1,b2,b3E"
    """
    string = string.strip('\n')
    if string[0] == 'B' and string[-1] == 'E':
        pass
    else:
        raise ValueError("Head or end is missed, data may be not complete.")
    
    result = string[1:-1].split(',')
    for i in range(6):
        result[i] = float(result[i])

    for i in range(5,9):
        result[i] = int(result[i])

    return result


# ==============================
# initialization
# ==============================
com = 'com3'
print 'opening %s...'%com
#ser = serial.Serial(com)
#print 'serial opened!'
#print 'clear serial buffer...'
# clear buffer
#ser.flush()
#ser.readline()


# ==============================
# main loop
# ==============================
if __name__ == '__main__':
    with serial.Serial(com) as ser:
        while True:
            try:
                raw_data = ser.readline()
                raw_data = parse_data(raw_data)
                buttons = {}
                buttons['lf'] = raw_data[6]
                buttons['ri'] = raw_data[7]
                buttons[3]    = raw_data[8]
            except (ValueError):
                continue

            mouse.MouseMain(raw_data[0:3], buttons)
    

    
